package Util;

import Dao.Impl.FinancialProductTaskDAOImpl;
import Dao.Impl.TransactionDAOImpl;
import Dao.Impl.UserDAOImpl;
import Model.FinancialProductTask;
import Model.Transaction;
import Model.User;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ProcessFinancialProductsJob implements Job {
    private static final Logger logger = LogManager.getLogger(ProcessFinancialProductsJob.class);

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("开始处理到期理财产品任务：{}", new Date());

        try (Connection conn = DbConnector.getConnection()) {
            UserDAOImpl userDAO = new UserDAOImpl();
            TransactionDAOImpl transactionDAO = new TransactionDAOImpl();
            FinancialProductTaskDAOImpl financialProductTaskDAO = new FinancialProductTaskDAOImpl();

            // 获取所有理财产品任务
            List<FinancialProductTask> allFinancialProductTasks = financialProductTaskDAO.getAllFinancialProductTasks();

            conn.setAutoCommit(false); // 开启事务
            try {
                for (FinancialProductTask task : allFinancialProductTasks) {

                    ZonedDateTime localNow = ZonedDateTime.now(); // 默认使用系统时区
                    ZonedDateTime maturityDateUtc = task.getMaturityDate().toInstant().atZone(ZoneId.of("UTC"));

                    // 判断任务是否达到收益日期
                    if (maturityDateUtc.compareTo(localNow) <= 0) {
                        // 获取用户和理财产品的相关信息
                        int userId = task.getUserId();
                        double expectedEarnings = task.getExpectedEarnings();

                        // 更新用户余额
                        User user = userDAO.getUserById(userId);
                        if (user == null) {
                            logger.warn("用户 ID {} 不存在，跳过处理。", userId);
                            continue;
                        }
                        user.setBalance(user.getBalance() + expectedEarnings);
                        userDAO.updateUser(user);

                        // 添加交易记录
                        Transaction transaction = new Transaction();
                        transaction.setUserId(userId);
                        transaction.setTransactionType("理财收益");
                        transaction.setAmount(expectedEarnings);
                        transaction.setTotalBalance(user.getBalance());
                        transaction.setDescription("理财产品收益到账");
                        transactionDAO.addTransaction(transaction);

                        // 完成后 修改任务时间为下一年
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(new Date());
                        calendar.add(Calendar.YEAR, 1);
                        task.setMaturityDate(new Timestamp(calendar.getTimeInMillis()));

                        // 更新理财产品任务的到期日期
                        financialProductTaskDAO.updateFinancialProductTask(task);
                    }
                }
                conn.commit(); // 提交事务
                logger.info("到期理财产品处理完成。");
            } catch (Exception e) {
                conn.rollback(); // 回滚事务
                logger.error("处理到期理财产品时出错，事务已回滚: {}", e.getMessage(), e);
            } finally {
                conn.setAutoCommit(true);
            }
        } catch (SQLException e) {
            logger.error("连接数据库时出错: {}", e.getMessage(), e);
        }
    }
}